<?php

namespace app\admin\business;

use app\common\model\mysql\AdminUser as AdminUserModel;

class AdminUser {

    public $userModelObj = null;

    public function __construct() {
        $this->userModelObj = new AdminUserModel();
    }

    /**
     * 登录验证
     * @param $data
     * @return bool|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login($data) {
        // 用户验证
        $user = $this->getAdminUserByUsername($data['username']);
        if (!$user) {
            return show(config('status.error'), "不存在该用户");
        }

        // 密码验证
        if ($user['password'] != md5($data['password'] . config("admin.passwd_salt"))) {
            return show(config('status.error'), "输入的密码错误");
        }

        // 记录session
        session(config('admin.session_admin'), $user);

        // 更新表的数据
        $updateData = [
            "last_time" => time(),
            "last_ip" => request()->ip(),
        ];
        $res = $this->userModelObj->updateById($user['id'], $updateData);
        return $res;
    }

    /**
     * @param $username
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAdminUserByUsername($username) {
        $user = $this->userModelObj->getAdminUserByUsername($username);
        if (empty($user) || $user->status != config("status.mysql.table_normal")) {
            return [];
        }
        return $user->toArray();
    }
}